package ThreadDemo.ThreadDemo7.ThreadDemo8;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * Created with IntelliJ IDEA.
 * Description: 利用原子性来解决线程安全问题
 * User:周次煜
 * Date: 2024-07-27
 * Time：15:16
 */

public class atom {

    // 原子性的整型数字
    private static AtomicInteger atomicInteger = new AtomicInteger();


    public static void main(String[] args) throws InterruptedException {



        Thread t1= new Thread(()->{
            for (int i = 0; i < 500000; i++) {
                // 进行加操作
               atomicInteger.incrementAndGet();

               // 减操作
//               atomicInteger.decrementAndGet();

            }
        });

        Thread t2= new Thread(()->{
            for (int i = 0; i < 500000; i++) {
                atomicInteger.incrementAndGet();
            }
        });


        t1.start();
        t2.start();


        t1.join();
        t2.join();

        System.out.println(atomicInteger.get());
    }
}
